#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re

class CSS():
    """css pack|human output_file.css file1.css [file2.css ... fileN.css]"""
    def __init__(self, format, files):
        self.join_keys = True
        
        self.format = format
        self.output_file = open(files[0], "w")
        self.file_names = files[1:]
        self.list_elements = []
        self.list_classes = []
        self.list_ids = []
        self.dict_elements = {}
        self.dict_classes = {}
        self.dict_ids = {}

        self.__read_files__()
        self.__make_output__()
    
    def __del__(self):
        self.output_file.close()
    
    def __read_files__(self):
        for file_name in self.file_names:
            f = open(file_name, "r")
            self.__analyse__("".join(f.readlines()))
            f.close()
    
    def __format__(self, elements):
        TAB = '\t'
        EOL = '\n'
        if self.format == "pack":
            TAB = ''
            EOL = ''
            
        for el in elements:
            self.output_file.write("%s {%s" % (el['key'].strip(), EOL))
            for item in el['items']:
                self.output_file.write("%s%s;%s" % (TAB, item.strip(), EOL))
            self.output_file.write("}%s%s" % (EOL, EOL))
    
    def __analyse__(self, content):
        content = re.sub(r"\n", '', content)
        content = re.sub(r"\t", '', content)
        content = re.sub(r"/\*.*?\*/", '', content)
        for keys, items in re.findall(r"(.*?){(.*?)}", content):
            self.__organize_keys__(keys, items)
    
    def __organize_item__(self, items):
        __items = []
        items = [item for item in items.split(';') if item != '']
        for item in items:
            split_items = item.split(':')
            if len(split_items) == 2: 
                __items.append("%s: %s" % \
                               (split_items[0].strip(), \
                                split_items[1].strip()))
        return sorted(__items, key=str.lower)
        
    def __organize_keys__(self, keys, items):
        items = self.__organize_item__(items)
        for key in \
                [key.strip() for key in keys.split(',') if key.strip() != ""]:
            if key[0] == '.':
                self.dict_classes.update({key: items})
                self.list_classes.append({'key': key, 'items': items})
            elif key[0] == '#':
                self.dict_ids.update({key: items})
                self.list_ids.append({'key': key, 'items': items})
            else:
                self.dict_elements.update({key: items})
                self.list_elements.append({'key': key, 'items': items})
    
    def __make_output__(self):
        elements = []
        classes = []
        ids = []
        
        if self.join_keys == False:
            elements = self.list_elements
            classes = self.list_classes
            ids = self.List_ids
        else:
            for key in self.dict_classes.keys():
                classes.append({"key": key, "items": self.dict_classes[key]})
            for key in self.dict_ids.keys():
                ids.append({"key": key, "items": self.dict_ids[key]})
            for key in self.dict_elements.keys():
                elements.append({"key": key, "items": self.dict_elements[key]})

        elements.sort(key=lambda v: v['key'].lower())
        classes.sort(key=lambda v: v['key'].lower())
        ids.sort(key=lambda v: v['key'].lower())

        try: 
            self.output_file.write(self.__format__(elements)) 
        except: 
            pass
        try:
            self.output_file.write(self.__format__(classes))
        except:
            pass
        try:
            self.output_file.write(self.__format__(ids))
        except:
            pass
            

if __name__ == '__main__':
    import sys
    if len(sys.argv) > 3:
        CSS(sys.argv[1], sys.argv[2:])
    else:
        print CSS.__doc__
